package com.ntd.study.algorithm.reduce.test1;

import com.ntd.study.algorithm.reduce.StudyReduceMes;

public class Contraction {

    public static void main(String[] args) {
        String resultString = compactString(StudyReduceMes.mes);
        System.out.println("压缩后字符串内容："+resultString);
        System.out.println("压缩后字符串大小："+resultString.length());

        String convertString = decompressionString(resultString);
        System.out.println("解压后字符串内容："+convertString);
        System.out.println("解压后字符串大小："+convertString.length());
    }

    public static String decompressionString(String tempString){
        char[] tempBytes = tempString.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < tempBytes.length; i++) {
            char c = tempBytes[i];
            char firstCharacter = (char) (c >>> 8);
            char secondCharacter = (char) ((byte)c);
            sb.append(firstCharacter);
            if(secondCharacter != 0)
                sb.append(secondCharacter);
        }
        return sb.toString();
    }


    public static String compactString(String tempString) {
        StringBuffer sb = new StringBuffer();
        byte[] tempBytes = tempString.getBytes();
        for (int i = 0; i < tempBytes.length; i+=2) {
            char firstCharacter = (char)tempBytes[i];
            char secondCharacter = 0;
            if(i+1<tempBytes.length)
                secondCharacter = (char)tempBytes[i+1];
            firstCharacter <<= 8;
            sb.append((char)(firstCharacter+secondCharacter));
        }
        return sb.toString();
    }
}